package org.springframework.security.oauth2.provider.error;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

@Deprecated
public abstract class AbstractOAuth2SecurityExceptionHandler {

    protected final Log logger = LogFactory.getLog(getClass());

    private WebResponseExceptionTranslator<?> exceptionTranslator = new DefaultWebResponseExceptionTranslator();

    private OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();

    // This is from Spring MVC.
    private HandlerExceptionResolver handlerExceptionResolver = new DefaultHandlerExceptionResolver();

    public void setExceptionTranslator(WebResponseExceptionTranslator<?> exceptionTranslator) {
        this.exceptionTranslator = exceptionTranslator;
    }

    public void setExceptionRenderer(OAuth2ExceptionRenderer exceptionRenderer) {
        this.exceptionRenderer = exceptionRenderer;
    }

    final void doHandle(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException, ServletException {
        try {
            ResponseEntity<?> result = exceptionTranslator.translate(authException);
            result = enhanceResponse(result, authException);
            exceptionRenderer.handleHttpEntityResponse(result, new ServletWebRequest(request, response));
            response.flushBuffer();
        } catch (ServletException e) {
            // Re-use some of the default Spring dispatcher behaviour - the exception came from the filter chain and
            // not from an MVC handler so it won't be caught by the dispatcher (even if there is one)
            if (handlerExceptionResolver.resolveException(request, response, this, e) == null) {
                throw e;
            }
        } catch (IOException e) {
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            // Wrap other Exceptions. These are not expected to happen
            throw new RuntimeException(e);
        }
    }

    protected ResponseEntity<?> enhanceResponse(ResponseEntity<?> result, Exception authException) {
        return result;
    }
}
